﻿/*
    Copyright (c) 2007 - 2009, Carlos Guzmán Álvarez

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
    are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright notice, 
          this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright notice, 
          this list of conditions and the following disclaimer in the documentation and/or 
          other materials provided with the distribution.
        * Neither the name of the author nor the names of its contributors may be used to endorse or 
          promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED2 TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Framework.Net.Xmpp.Core;
using Framework.Net.Xmpp.InstantMessaging.Configuration;
using Framework.Net.Xmpp.Serialization.Extensions;
using Framework.Net.Xmpp.Serialization.InstantMessaging.Client;

namespace Framework.Net.Xmpp.InstantMessaging
{
    /// <summary>
    /// XMPP Instant Messaging Session
    /// </summary>
	public sealed class XmppSession
    {
        #region · Events ·

        /// <summary>
        /// Occurs when a new normal message is received.
        /// </summary>
        public event EventHandler<XmppMessageReceivedEventArgs> NormalMessageReceived;

        /// <summary>
        /// Occurs when a new headline message is received from the XMPP server.
        /// </summary>
        public event EventHandler<XmppMessageReceivedEventArgs> HeadlineMessageReceived;

        /// <summary>
        /// Occurs when a new error message is received from the XMPP server.
        /// </summary>
        public event EventHandler<XmppMessageReceivedEventArgs> ErrorMessageReceived;

        /// <summary>
		/// Occurs when the session state changes.
		/// </summary>
        public event EventHandler<XmppSessionStateChangedEventArgs> StateChanged;

        /// <summary>
        /// Occurs when an incoming chat message is received 
        /// </summary>
        public event EventHandler<XmppMessageReceivedEventArgs> ChatMessageReceived;

        #endregion

		#region · Fields ·

		private XmppConnection                  connection;
		private XmppRoster                      roster;
        private XmppPresence                    presence;
        private XmppSessionEntityCapabilities   capabilities;
        private XmppSessionConfiguration        configuration;
        private XmppSessionState                state;
        private Dictionary<string, XmppChat>    chats;
        private object                          syncObject;        

		#endregion

        #region · Properties ·

        /// <summary>
        /// Gets the User <see cref="XmppJid">JID</see>
        /// </summary>
		public XmppJid UserId
		{
			get
			{
				if (this.connection != null)
				{
					return this.connection.UserId;
				}

				return null;
			}
		}

        /// <summary>
        /// Gets the session <see cref="XmppRoster">Roster</see>
        /// </summary>
		public XmppRoster Roster
		{
			get 
			{ 
				if (this.roster == null)
				{
                    this.roster = new XmppRoster(this);
				}

				return this.roster; 
			}
		}

        /// <summary>
        /// Gets the client session supported features
        /// </summary>
        public XmppSessionEntityCapabilities Capabilities
        {
            get
            {
                if (this.capabilities == null)
                {
                    this.capabilities = new XmppSessionEntityCapabilities(this);
                }

                return this.capabilities;
            }
        }

        /// <summary>
        /// Gets the XMPP session configuration
        /// </summary>
        public XmppSessionConfiguration Configuration
        {
            get { return this.configuration; }
        }

        /// <summary>
        /// Gets the session state
        /// </summary>
        public XmppSessionState State
        {
            get { return this.state; }
            private set
            {
                if (this.state != value)
                {
                    this.state = value;

                    if (this.StateChanged != null)
                    {
                        this.StateChanged(this, new XmppSessionStateChangedEventArgs(this.State));
                    }
                }
            }
        }

        public XmppPresence Presence
        {
            get
            {
                if (this.presence == null)
                {
                    this.presence = new XmppPresence(this);
                }

                return this.presence;
            }
        }

        #endregion

        #region · Internal Properties ·

        internal XmppConnection Connection
        {
            get { return this.connection; }
        }

        #endregion

        #region · Constructors ·

        /// <summary>
        /// Initializes a new instance of the <see cref="XmppSession"/> class
        /// </summary>
        public XmppSession()
		{
            this.configuration  = XmppSessionConfiguration.GetConfiguration();
            this.chats          = new Dictionary<string, XmppChat>();
            this.syncObject     = new object();
            this.connection     = new XmppConnection();
		}

		#endregion

		#region · Methods ·

		/// <summary>
		/// Opens a new Session with the given connection parameters
		/// </summary>
		/// <param name="connectionString">Connection parameters</param>
		public void Open(string connectionString)
		{
			if (this.connection != null && this.connection.State == XmppConnectionState.Open)
			{
				throw new XmppException("The session is already open");
			}

            this.State = XmppSessionState.LoggingIn;

            // Wire XmppConnection events
            this.WireXmppConnection();

            // Perform the authentication
			this.connection.Open(connectionString);

            if (this.connection != null && this.connection.State == XmppConnectionState.Open)
            {
                // Send Roster Request
                this.Roster.RequestRosterList();

                // Set initial Presence status
                this.Presence.SetInitialPresence();

                // Advertise Capabilities
                this.Capabilities.AdvertiseCapabilities();

                // Set as Logged In
                this.State = XmppSessionState.LoggedIn;
            }
            else
            {
                this.State = XmppSessionState.Error;
            }
        }

        /// <summary>
        /// Closes the Session
        /// </summary>
        public void Close()
        {
            if (this.connection != null && 
                (this.connection.State == XmppConnectionState.Opening ||
                this.connection.State == XmppConnectionState.Open))
            {
                try
                {
                    this.State = XmppSessionState.LoggingOut;

                    if (this.connection.State == XmppConnectionState.Open)
                    {
                        // Save session configuration
                        this.Configuration.Save();

                        // Change presence to unavailable
                        this.SetUnavailable();

                        // Clear all chats
                        this.chats.Clear();
                    }

                    // Close connection
                    this.connection.Close();

                    // Unwire XmppConnection events
                    this.UnwireXmppConnection();
                }
                catch
                {
                }
                finally
                {
                    this.State  = XmppSessionState.LoggedOut;
                }
            }
        }

        /// <summary>
        /// Checks if a given user has an open chat session
        /// </summary>
        /// <param name="contactId"></param>
        /// <returns></returns>
        public bool HasOpenChat(string contactId)
        {
            return (this.chats != null && this.chats.ContainsKey(contactId));
        }

        /// <summary>
        /// Checks if a given user has an open chat session
        /// </summary>
        /// <param name="contactId"></param>
        /// <returns></returns>
        public bool HasOpenChat(XmppJid contactId)
        {
            return this.HasOpenChat(contactId.BareIdentifier);
        }

        /// <summary>
        /// Publishes the display name.
        /// </summary>
        /// <param name="displayName">The display name.</param>
        public void PublishDisplayName(string displayName)
        {
            // Publish the display name ( nickname )
            IQ      iq      = new IQ();
            VCard   vcard   = new VCard();

            iq.ID   = XmppIdentifierGenerator.Generate();
            iq.Type = IQType.Set;
            iq.From = this.UserId.ToString();

            vcard.NickName = displayName;

            iq.Items.Add(vcard);

            this.Send(iq);
        }

        /// <summary>
        /// Publishes the avatar.
        /// </summary>
        /// <param name="mimetype">The mimetype.</param>
        /// <param name="hash">The hash.</param>
        /// <param name="originalAvatar">The original avatar data.</param>
        /// <param name="onlineAvatar">The online state avatar data.</param>
        public void PublishAvatar(string mimetype, string hash, Image originalAvatar, Image onlineAvatar)
        {
            MemoryStream avatarData = new MemoryStream();

            try
            {
                originalAvatar.Save(avatarData, ImageFormat.Png);

                // Publish the avatar
                IQ      iq      = new IQ();
                VCard   vcard   = new VCard();

                iq.ID   = XmppIdentifierGenerator.Generate();
                iq.Type = IQType.Set;
                iq.From = this.UserId.ToString();

                vcard.Photo.Type    = mimetype;
                vcard.Photo.Photo   = avatarData.ToArray();

                iq.Items.Add(vcard);

                this.Send(iq);

                // Save the avatar
                this.configuration.SaveAvatar(this.UserId.BareIdentifier, hash, originalAvatar, onlineAvatar);

                // Update session configuration
                this.configuration.Save();
            }
            catch
            {
                throw;
            }
            finally
            {
                if (avatarData != null)
                {
                    avatarData.Close();
                    avatarData.Dispose();
                    avatarData = null;
                }
            }
        }

        #endregion

        #region · Create Methods ·

        /// <summary>
        /// Creates the chat.
        /// </summary>
        /// <param name="contactId">The contact id.</param>
        /// <returns></returns>
        public XmppChat CreateChat(string contactId)
        {
            return this.CreateChat(new XmppJid(contactId));
        }

        /// <summary>
        /// Creates the chat.
        /// </summary>
        /// <param name="contactId">The contact id.</param>
        /// <returns></returns>
        public XmppChat CreateChat(XmppJid contactId)
        {
            this.CheckSessionState();

            XmppChat chat = null;

            lock (this.syncObject)
            {
                if (!this.chats.ContainsKey(contactId.BareIdentifier))
                {
                    chat = new XmppChat(this, this.Roster[contactId.BareIdentifier]);
                    this.chats.Add(contactId.BareIdentifier, chat);

                    chat.ChatClosed += new EventHandler(OnChatClosed);
                }
                else
                {
                    chat = this.chats[contactId.BareIdentifier];
                }
            }

            return chat;
        }

        /// <summary>
        /// Creates the chat room.
        /// </summary>
        /// <param name="chatRoomName">Name of the chat room.</param>
        /// <returns></returns>
        public XmppChatRoom CreateChatRoom(string chatRoomName)
        {
            /*
            this.CheckSessionState();

            XmppService     service     = this.GetService(XmppServiceCategory.Conference);
            XmppChatRoom    chatRoom    = null;
            string          chatRoomId  = String.Format("{0}/{1}", service.ServiceId.BareIdentifier, chatRoomName);

            if (service != null)
            {
                chatRoom    = new XmppChatRoom(this, service, new XmppJid(chatRoomId));
                chatRoomId  = String.Format("{0}/{1}", service.ServiceId.BareIdentifier, chatRoomName);

                if (!chatRoom.CreateChatRoom())
                {
                    throw new XmppException(String.Format("Unable to create the chat room ( {0} )", chatRoomName));
                }
            }

            return chatRoom;
            */

            throw new NotImplementedException();
        }

        /// <summary>
        /// Enters the chat room.
        /// </summary>
        /// <param name="chatRoomName">Name of the chat room.</param>
        /// <returns></returns>
        public XmppChatRoom EnterChatRoom(string chatRoomName)
        {
            /*
            this.CheckSessionState();
            
            XmppService     service     = this.GetService(XmppServiceCategory.Conference);
            XmppChatRoom    chatRoom    = null;
            string          chatRoomId  = String.Format("{0}/{1}", service.ServiceId.BareIdentifier, chatRoomName);

            if (service != null)
            {
                chatRoom    = new XmppChatRoom(this, service, new XmppJid(chatRoomId));
                chatRoomId  = String.Format("{0}/{1}", service.ServiceId.BareIdentifier, chatRoomName);

                if (!chatRoom.SeekEnterChatRoom())
                {
                    throw new XmppException(String.Format("Unable to enter in the requested chat room ( {0} )", chatRoomName));
                }
            }

            return chatRoom;
            */

            throw new NotImplementedException();
        }

        #endregion

        #region · Presence Methods ·

        /// <summary>
        /// Sets as unavailable.
        /// </summary>
        public void SetUnavailable()
        {
            this.CheckSessionState();

            this.Presence.SetUnavailable();
        }

        /// <summary>
        /// Sets the presence.
        /// </summary>
        /// <param name="showAs">The show as.</param>
        public void SetPresence(XmppPresenceState showAs)
        {
            this.SetPresence(showAs, null);
        }

        /// <summary>
        /// Sets the presence.
        /// </summary>
        /// <param name="showAs">The show as.</param>
        /// <param name="status">The status.</param>
        public void SetPresence(XmppPresenceState newPresence, string status)
        {
            switch (newPresence)
            {
                case XmppPresenceState.Invisible:
                    throw new NotImplementedException();
                    break;

                case XmppPresenceState.Offline:
                    this.Close();
                    break;

                default:
                    this.SetPresence(newPresence, status, 0);
                    break;
            }
        }

        /// <summary>
        /// Sets the presence.
        /// </summary>
        /// <param name="showAs">The show as.</param>
        /// <param name="status">The status.</param>
        /// <param name="priority">The priority.</param>
        public void SetPresence(XmppPresenceState showAs, string status, int priority)
        {
            this.CheckSessionState();

            this.Presence.SetPresence(showAs, status);
        }

        #endregion

        #region · Internal Methods ·

        /// <summary>
        /// Sends a XMPP message to the server
        /// </summary>
        /// <param name="message">The message to be sent</param>
        internal void Send(object message)
        {
            this.connection.Send(message);
        }

        #endregion

		#region · Private Methods ·

        private void WireXmppConnection()
        {
            this.connection.AuthenticationFailiure  += new EventHandler<XmppAuthenticationFailiureEventArgs>(OnAuthenticationFailiure);
            this.connection.NormalMessageReceived   += new EventHandler<XmppMessageReceivedEventArgs>(OnNormalMessageReceived);
            this.connection.HeadlineMessageReceived += new EventHandler<XmppMessageReceivedEventArgs>(OnHeadlineMessageReceived);
            this.connection.ChatMessageReceived     += new EventHandler<XmppMessageReceivedEventArgs>(OnChatMessageReceived);
            this.connection.ErrorMessageReceived    += new EventHandler<XmppMessageReceivedEventArgs>(OnErrorMessageReceived);
        }

        private void UnwireXmppConnection()
        {
            this.connection.AuthenticationFailiure  -= new EventHandler<XmppAuthenticationFailiureEventArgs>(OnAuthenticationFailiure);
            this.connection.NormalMessageReceived   -= new EventHandler<XmppMessageReceivedEventArgs>(OnNormalMessageReceived);
            this.connection.HeadlineMessageReceived -= new EventHandler<XmppMessageReceivedEventArgs>(OnHeadlineMessageReceived);
            this.connection.ChatMessageReceived     -= new EventHandler<XmppMessageReceivedEventArgs>(OnChatMessageReceived);
            this.connection.ErrorMessageReceived    -= new EventHandler<XmppMessageReceivedEventArgs>(OnErrorMessageReceived);
        }

		private void CheckSessionState()
		{
			if (this.connection == null || this.connection.State != XmppConnectionState.Open)
			{
				throw new XmppException("The session is not valid.");
			}
		}

		#endregion

        #region · XmppConnection Event Handlers ·

        private void OnAuthenticationFailiure(object sender, XmppAuthenticationFailiureEventArgs e)
        {
            this.Close();
        }

        private void OnNormalMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
            if (this.NormalMessageReceived != null)
            {
                this.NormalMessageReceived(this, e);
            }
        }

        private void OnHeadlineMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
            if (this.HeadlineMessageReceived != null)
            {
                this.HeadlineMessageReceived(this, e);
            }
        }

        private void OnChatMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
            XmppChat chat = null;

            if (!this.chats.ContainsKey(e.Message.From.BareIdentifier))
            {
                chat = this.CreateChat(e.Message.From);
            }
            else
            {
                chat = this.chats[e.Message.From.BareIdentifier];
            }

            chat.ChatMessageReceived(e);

            if (this.ChatMessageReceived != null)
            {
                this.ChatMessageReceived(this, e);
            }
        }

        private void OnErrorMessageReceived(object sender, XmppMessageReceivedEventArgs e)
        {
            if (this.ErrorMessageReceived != null)
            {
                this.ErrorMessageReceived(this, e);
            }
        }

        private void OnChatClosed(object sender, EventArgs e)
        {
            XmppChat chat = (XmppChat)sender;

            if (chat != null)
            {
                chat.ChatClosed -= new EventHandler(OnChatClosed);

                if (chat.Contact != null)
                {
                    this.chats.Remove(chat.Contact.ContactId.BareIdentifier);
                }
            }
        }

        #endregion
    }
}
